package it.xiuxian.personcenter.activity

import android.Manifest
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseActivity
import it.xiuxian.lib.utils.Util
import it.xiuxian.personcenter.R
import it.xiuxian.personcenter.databinding.ActivityInviteBinding
import it.xiuxian.personcenter.presenter.InviteFriendsActivityPresenter
import kotlinx.android.synthetic.main.activity_invite.*
import java.io.FileOutputStream
import java.lang.ref.WeakReference

@Route(path = ArouterAddress.INVITEFRIENDSACTIVITY)
class InviteFriendsActivity: BaseActivity<InviteFriendsActivityPresenter>(){
    @JvmField
    @Autowired
    var erweima:String?=null
    @JvmField
    @Autowired
    var yaoqingma:String?=null
    var binding:ActivityInviteBinding?=null
    fun myPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (ContextCompat.checkSelfPermission(
                            this,
                            Manifest.permission.READ_PHONE_STATE
                    ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                            this,
                            Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                            this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(
                        arrayOf(
                                Manifest.permission.READ_PHONE_STATE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.ACCESS_FINE_LOCATION
                        ), PackageManager.PERMISSION_GRANTED
                )
            }
        }
    }
    /**
     * 屏幕截图
     */
    fun screenShot1(activity: Activity){
        //val filepath = "/sdcard/screenShot.png"
        var bitmap: Bitmap? = null
        try{
            Log.e("whh0914", "111开始屏幕截图...")
            regToWx()
            //截图
            activity.getWindow().getDecorView().setDrawingCacheEnabled(true)
            bitmap = activity.getWindow().getDecorView().getDrawingCache()

            /*//保存图片
            val fos = FileOutputStream(filepath)
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos)*/
            Log.e("bitmap", bitmap.byteCount.toString())
            val imgObj  = WXImageObject(bitmap)
            val msg = WXMediaMessage()

//用 WXTextObject 对象初始化一个 WXMediaMessage 对象
//用 WXTextObject 对象初始化一个 WXMediaMessage 对象
            //val msg = WXMediaMessage()
            msg.mediaObject = imgObj
            val thumbBmp = Bitmap.createScaledBitmap(bitmap,150, 150, true)
           //bitmap.recycle()
            msg.thumbData= Util.bmpToByteArray(thumbBmp, true)
            // =Util.bmpToByteArray(thumbBmp, true);
            val req = SendMessageToWX.Req()
            req.transaction = System.currentTimeMillis().toString() //transaction字段用与唯一标示一个请求
            req.message = msg
            req.scene = mTargetScene
            //调用api接口，发送数据到微信
            api!!.sendReq(req)
            //sendWx(bitmap)
        } catch (e: Exception) {
            Log.e("whh0914", "111屏幕截图出现异常：$e")
        }
    }


    override val layoutId: Int
        get() = R.layout.activity_invite
    override val presenter: InviteFriendsActivityPresenter
        get() = InviteFriendsActivityPresenter()

    override fun initView(){
        ARouter.getInstance().inject(this)
       binding = getViewDataBinding<ActivityInviteBinding>()
        setTitle("邀请好友")
        myPermission()
        binding!!.tvYaoqingmaContent.text =yaoqingma
        Glide.with(this).applyDefaultRequestOptions(
                RequestOptions().diskCacheStrategy(
                        DiskCacheStrategy.NONE).skipMemoryCache(true)).load(erweima).into(binding!!.image1)
        binding!!.ivBack.setOnClickListener { finish() }
        binding!!.ivFen.setOnClickListener {
            screenShot1(this)
        }
    }
    var handler = MyHandler(this)

    //kotlin 静态内部类   加了inner为非静态
    class MyHandler(activity: InviteFriendsActivity?) : Handler() {
        var mactivity: WeakReference<InviteFriendsActivity> = WeakReference<InviteFriendsActivity>(activity)
        override fun handleMessage(msg: Message) {
            if (mactivity.get()==null)
                return
            super.handleMessage(msg)
            when (msg.what) {
                100 -> {
                }
                else -> {
                }
            }
        }

    }

    // APP_ID 替换为你的应用从官方网站申请到的合法appID
    private val APP_ID = "wxf58b045a6e5b7f2b"

    // IWXAPI 是第三方app和微信通信的openApi接口
    private var api: IWXAPI? = null
    private fun regToWx(){
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true)

        // 将应用的appId注册到微信
        api!!.registerApp(APP_ID)

        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {

                // 将该app注册到微信
                api!!.registerApp(APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }
    private val mTargetScene = SendMessageToWX.Req.WXSceneSession
    lateinit var bitmap:Bitmap
    private fun sendWx(bitmap: Bitmap){
        //初始化一个 WXTextObject 对象，填写分享的文本内容
        //初始化一个 WXTextObject 对象，填写分享的文本内容


        /* // msg.mediaObject = textObj
          msg.description = HttpConfig.BASE_URL+"/zixun/index.html?id="+id+"&pic="+erweima*/
        // val thumbBmp: Bitmap = BitmapFactory.decodeResource(resources, R.mipmap.anquanzhongxin)
        /* Thread(Runnable{
           var mybitmap =  Glide.with(this).asBitmap()
                     .load(imaurl).submit(100,100).get()
              bitmap= Bitmap.createBitmap(mybitmap,0,0,mybitmap.width,mybitmap.height)

            }).start()*/
        //  Log.e("bitmap",bitmap.toString())
        /*  buffer = ByteBuffer.allocate(bitmap.byteCount)
          bitmap.copyPixelsToBuffer(buffer)
         var d =  buffer.array().size
          Log.e("bitmap",d.toString())*/

        /* var buffer = ByteBuffer.allocate(thumbBmp.byteCount)
           thumbBmp.copyPixelsToBuffer(buffer)
           msg.thumbData= buffer.array()
          // =Util.bmpToByteArray(thumbBmp, true);
           val req = SendMessageToWX.Req()
           req.transaction = System.currentTimeMillis().toString() //transaction字段用与唯一标示一个请求

           req.message = msg
           req.scene = mTargetScene
   //调用api接口，发送数据到微信
           api!!.sendReq(req)*/
    }


}